package com.ushio.capsuleservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ushio.capsuleservice.model.dto.ApiResponse;
import com.ushio.capsuleservice.model.entity.Archive;
import com.ushio.capsuleservice.model.entity.ArchiveNote;
import com.ushio.capsuleservice.service.ArchiveService;
import com.ushio.capsuleservice.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 思维存档控制器
 */
@RestController
@RequestMapping("/api/archive")
@CrossOrigin(origins = "*")
public class ArchiveController {
    
    @Autowired
    private ArchiveService archiveService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 创建思维存档
     */
    @PostMapping
    public ApiResponse<Archive> createArchive(@RequestBody Archive archive, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            archive.setUserId(userId);
            
            Archive createdArchive = archiveService.createArchive(archive);
            return ApiResponse.success("创建成功", createdArchive);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户的思维存档列表
     */
    @GetMapping
    public ApiResponse<IPage<Archive>> getUserArchives(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            IPage<Archive> archives = archiveService.getUserArchives(userId, page, size, keyword);
            return ApiResponse.success(archives);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取思维存档详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Archive> getArchiveDetail(@PathVariable Long id) {
        try {
            Archive archive = archiveService.getArchiveDetail(id);
            if (archive == null) {
                return ApiResponse.error("思维存档不存在");
            }
            return ApiResponse.success(archive);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 更新思维存档
     */
    @PutMapping("/{id}")
    public ApiResponse<Archive> updateArchive(@PathVariable Long id, @RequestBody Archive archive, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 检查是否是存档作者
            Archive existingArchive = archiveService.getById(id);
            if (existingArchive == null || !existingArchive.getUserId().equals(userId)) {
                return ApiResponse.error("无权限修改此存档");
            }
            
            Archive updatedArchive = archiveService.updateArchive(id, archive);
            return ApiResponse.success("更新成功", updatedArchive);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除思维存档
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteArchive(@PathVariable Long id, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 检查是否是存档作者
            Archive existingArchive = archiveService.getById(id);
            if (existingArchive == null || !existingArchive.getUserId().equals(userId)) {
                return ApiResponse.error("无权限删除此存档");
            }
            
            boolean success = archiveService.deleteArchive(id);
            if (success) {
                return ApiResponse.success("删除成功", null);
            } else {
                return ApiResponse.error("删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 添加存档备注
     */
    @PostMapping("/{id}/note")
    public ApiResponse<ArchiveNote> addArchiveNote(@PathVariable Long id, @RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        try {
            String token = getTokenFromRequest(httpRequest);
            Long userId = jwtUtil.getUserIdFromToken(token);
            String content = request.get("content");
            
            ArchiveNote note = archiveService.addArchiveNote(id, content, userId);
            return ApiResponse.success("添加备注成功", note);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取存档备注列表
     */
    @GetMapping("/{id}/notes")
    public ApiResponse<IPage<ArchiveNote>> getArchiveNotes(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<ArchiveNote> notes = archiveService.getArchiveNotes(id, page, size);
            return ApiResponse.success(notes);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除存档备注
     */
    @DeleteMapping("/note/{noteId}")
    public ApiResponse<String> deleteArchiveNote(@PathVariable Long noteId, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            boolean success = archiveService.deleteArchiveNote(noteId, userId);
            if (success) {
                return ApiResponse.success("删除备注成功", null);
            } else {
                return ApiResponse.error("删除备注失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("未找到有效的token");
    }
}
